package cn.com.twoke.easyproject.modules.auth.service.impl;

import cn.com.twoke.easyproject.common.context.holder.UserLoginContextHolder;
import cn.com.twoke.easyproject.common.utils.IpUtils;
import cn.com.twoke.easyproject.common.utils.ServletUtils;
import cn.com.twoke.easyproject.modules.auth.event.UserLoginEvent;
import cn.com.twoke.easyproject.modules.auth.request.LoginRequest;
import cn.com.twoke.easyproject.modules.auth.service.LoginService;
import cn.com.twoke.easyproject.modules.auth.spi.AuthService;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.io.Serializable;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final ApplicationEventPublisher publisher;
    private final AuthService authService;

    @Override
    public String loginByUserNameAndPassword(LoginRequest request) {
        Serializable uid = authService.loginByUserNameAndPassword(request.getUsername(), request.getPassword());
        // 登录账号
        StpUtil.login(uid);
        // 初始化登录后的信息
        UserLoginContextHolder.init();
        // 发布登录事件
        publishLoginEvent((Long) uid);
        return StpUtil.getTokenValue();
    }

    /**
     * 发布用户登录事件
     * @param uid
     */
    private void publishLoginEvent(long uid) {
        String ip = IpUtils.getIp(ServletUtils.getRequest());
        String ip2region = IpUtils.getIp2region(ip);
        publisher.publishEvent(new UserLoginEvent(this, uid, ip, ip2region));
    }

}
